#include <header.h>
int main(int argc, char* argv[]){
	ARGS_CHECK(argc, 1);

	char *port = "8080";
	char *ip = "192.168.169.128";
	int socket_fd = socket(AF_INET, SOCK_STREAM, 0);

	struct sockaddr_in clientaddr;
	clientaddr.sin_family = AF_INET;
	clientaddr.sin_port = htons(atoi(port));
	clientaddr.sin_addr.s_addr = inet_addr(ip);

	int ret = connect(socket_fd, (struct sockaddr*)&clientaddr, sizeof clientaddr);
	ERROR_CHECK(ret, -1, "connect");

	int epoll_fd = epoll_create(1);

	struct epoll_event event_stdin;
	event_stdin.events = EPOLLIN;			/* 读取 */
	event_stdin.data.fd = STDIN_FILENO;	/* 指定文件描述符 */
	epoll_ctl(epoll_fd, EPOLL_CTL_ADD, STDIN_FILENO, &event_stdin);

	struct epoll_event event_socket;
	event_socket.events = EPOLLIN;			/* 读取 */
	event_socket.data.fd = socket_fd;	/* 指定文件描述符 */
	epoll_ctl(epoll_fd, EPOLL_CTL_ADD, socket_fd, &event_socket);

	bool server_alive = true;

	// 超时时间, 毫秒
	// @brief 重写，添加最后发消息时间
	time_t begin_time;
	time(&begin_time);

	while(server_alive){
		struct epoll_event list[8];
		int num = epoll_wait(epoll_fd, list, 8, 10 * 1000);
		ERROR_CHECK(num, -1, "epoll_wait");

		time_t curr_time;
		char buf[1 << 10] = {0};
		for(int i = 0; i < num; i++){
			if(list[i].data.fd == STDIN_FILENO){

				// TODO read stdin
				__bzero(buf, sizeof buf);			
				ssize_t ret1 = read(STDIN_FILENO, buf, sizeof buf);
				ERROR_CHECK(ret1, -1, "read from stdin");

				int ret2 = send(socket_fd, buf, sizeof buf, 0);
				ERROR_CHECK(ret2, -1, "send");

				time(&begin_time);
			
			}else if(list[i].data.fd == socket_fd){

				// read from socket
				__bzero(buf, sizeof buf);
				ssize_t byte = recv(socket_fd, buf, sizeof buf, 0);
				ERROR_CHECK(byte, -1, "recv");

				// 读到0个表示服务器挂了
				if(byte == 0){
					printf("服务器挂了\n");
					server_alive = false;
					break;
				}
				printf("%s\n", buf);
				
				time(&curr_time);
			}

		}
		if(num == 0 || curr_time - begin_time > 10){
			printf("超时断开\n");
			break;
		}

	}

	close(socket_fd);
	return 0;
}